package sweezy.swf.tools.flex
{
	import flash.utils.ByteArray;
	import mx.controls.DataGrid;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.ClassFactory;
	import mx.events.DataGridEvent;
	import sweezy.core.reflect.IProperty;

	public class PropertyView extends DataGrid
	{

		private var _column:DataGridColumn;

		private var _data:Array;

		private var _value:SWFNode;

		public function PropertyView()
		{
		}

		override public function set dataProvider(value:Object):void
		{
			value = value as SWFNode;
			if (_value === value)
			{
				return;
			}

			_value = value as SWFNode;
			_data = [];

			if (value !== null)
			{
				for each (var property:Property in _value.scalarProperties)
				{
					_data[_data.length] = new PropertyItem(property.name, property.type, _value.value);
				}
			}

			super.dataProvider = _data;
		}

		override protected function createChildren():void
		{
			super.createChildren();

			addEventListener(DataGridEvent.ITEM_EDIT_BEGINNING, itemEditBeginningHandler);
			_column = (document as Inspector).editColumn;
		}

		private function itemEditBeginningHandler(e:DataGridEvent):void
		{
			if (e.itemRenderer === null)
			{
				e.preventDefault();
				return;
			}

			var item:PropertyItem = e.itemRenderer.data as PropertyItem;
			if (item === null)
			{
				e.preventDefault();
				return;
			}

			var data:* = item.data;
			if (data === null || data is ByteArray)
			{
				e.preventDefault();
				return;
			}

			var editor:Class = TextArea;
			if (item.type === Boolean)
			{
				editor = BooleanEditor;
			}
			else if (item.type === int)
			{
				editor = IntEditor;
			}
			else if (item.type === uint)
			{
				editor = UintEditor;
			}
			else if (item.type === Number)
			{
				editor = TextInput;
			}
			_column.itemEditor = new ClassFactory(editor);
		}
	}
}

import mx.controls.ComboBox;
import mx.controls.NumericStepper;
import mx.controls.TextInput;
import sweezy.swf.tools.flex.PropertyItem;

class BooleanEditor extends ComboBox
{

	public function BooleanEditor()
	{
		dataProvider = [false, true];
	}

	override public function set data(value:Object):void
	{
		var item:PropertyItem = value as PropertyItem;

		super.data = item;

		var index:uint = 0;
		if (item !== null)
		{
			if (item.data)
			{
				index = 1;
			}
		}

		selectedIndex = index;
	}
}

class UintEditor extends NumericStepper
{

	public function UintEditor()
	{
		maximum = int.MAX_VALUE;
		minimum = int.MIN_VALUE;
	}

	public function get text():String
	{
		return String(value);
	}
}

class IntEditor extends NumericStepper
{

	public function IntEditor()
	{
		maximum = int.MAX_VALUE;
		minimum = int.MIN_VALUE;
	}

	public function get text():String
	{
		return String(value);
	}
}
